import axios from 'axios'
import { getToken, getTokenType } from '@/utils/auth'
import Vue from 'vue'
import { Toast } from 'vant'

Vue.use(Toast)

const isDevelopment = process.env.NODE_ENV === 'development';

const service = axios.create({
  withCredentials: true,
  timeout: 50000
})

// 请求拦截
service.interceptors.request.use(
  (config) => {
    config.headers['Authorization'] = getTokenType() + ' ' + getToken();
    const baseURL = localStorage.getItem('baseUrl') || '';
    config.baseURL = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_BASE_PATH : baseURL + process.env.VUE_APP_NGINX_PATH;
    //config.headers['ngrok-skip-browser-warning'] = "true";  //ngrok代理请求头
    if(isDevelopment){
      config.headers['x-request-wan-access'] = true;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
)

// 响应拦截
service.interceptors.response.use(
  (response) => {
    if (response.data.code != '200') {
      if (response.data.code == '3002') {
        // 回退到登录页
      } else if (response.data.code == '3005' || response.data.code == '3007') {
        // 登录过期 回退到登录页
      } else if (response.data.code == '300') {
        Toast(response.data.message)
      } else {
        // 错误提示
        // Notify({ type: 'danger', message: response.data.message })

        return response
      }
      // return Promise.reject(new Error(response.data.message || 'Error'))
    } else {
      return response
    }
  },
  (error) => {
    // 错误提示
    if (error.message == 'Network Error') {
      Toast('当前网络异常，请稍后重试')
    } else if (error == 'Error: timeout of 15000ms exceeded') {
      Toast('当前现场网络情况不佳，请检查现场网络后重试')
    } else {
      if (error.response.data.message) {
        Toast(error.response.data.message)
      } else {
        Toast(error.message)
      }
    }
    return Promise.reject(error)
  }
)

export default service
